package cn.com.dashihui.web.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.aop.Duang;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;

import cn.com.dashihui.kit.CommonKit;
import cn.com.dashihui.kit.DatetimeKit;
import cn.com.dashihui.kit.DirKit;
import cn.com.dashihui.kit.ExcelExportUtil.Pair;
import cn.com.dashihui.kit.UtilNumber;
import cn.com.dashihui.web.base.BaseController;
import cn.com.dashihui.web.common.RabbitMQCode;
import cn.com.dashihui.web.dao.Admin;
import cn.com.dashihui.web.dao.Category;
import cn.com.dashihui.web.dao.DetailsImg;
import cn.com.dashihui.web.dao.GoodsBaseImages;
import cn.com.dashihui.web.dao.GoodsItem;
import cn.com.dashihui.web.dao.GoodsSale;
import cn.com.dashihui.web.dao.GoodsSaleGT;
import cn.com.dashihui.web.dao.GoodsSaleItem;
import cn.com.dashihui.web.dao.GoodsSaleOption;
import cn.com.dashihui.web.dao.GoodsSaleSpec;
import cn.com.dashihui.web.dao.GoodsSaleTemplate;
import cn.com.dashihui.web.dao.GoodsStore;
import cn.com.dashihui.web.dao.GoodsStoreRel;
import cn.com.dashihui.web.rabbitmq.MsgSend;
import cn.com.dashihui.web.service.GoodsBaseService;
import cn.com.dashihui.web.service.GoodsStoreService;
import cn.com.dashihui.web.service.StoreService;

/**
 * 平台基础商品管理，基础商品可由各分公司进行复制
 */
public class GoodsBaseController extends BaseController{
	private GoodsBaseService service = Duang.duang(GoodsBaseService.class);
	private StoreService storeService = new StoreService();
	private GoodsStoreService goodstoreService = new GoodsStoreService();
	/**
	 * 转到商品列表页面
	 */
	public void index(){
		List<Record> list=storeService.findAllSeller();
    	setAttr("list", list);
		render("index.jsp");
	}
	/**
	 * 转到人气宝贝
	 */
	public void baby(){
		render("baby.jsp");
	}
	/**
	 * 列表页面异步请求数据
	 */
	public void page(){
		int pageNum = getParaToInt("pageNum", 0);
		if(pageNum==0){
			pageNum = getParaToInt(0, 1);
		}
		int pageSize = getParaToInt("pageSize", PropKit.getInt("constants.pageSize"));
		String sGoodName = getPara("sGoodName");
 		int sGoodId = getParaToInt("sGoodId",0);
 		String sSellerId = getPara("sSellerId");
 		String sStoreId = getPara("sStoreId");
		int state = getParaToInt("sState",0);
		int sGb = getParaToInt("sGb", 0);
		renderResult(0,service.findByPage(pageNum,pageSize,sGoodId,sGoodName,sGb,sSellerId,sStoreId,state));
	}
	//根据公司查询分公司
	public void chooseStore(){
		String[] sSellerId = getParaValues("sSellerId");
		String str = java.lang.String.join("','", sSellerId);
		renderSuccess(storeService.chooseStore(str));
	}
	// 根据用户查询用户所属公司，根据公司sellerId关联分公司sellerId查询分公司
	public void chooseAllStore() {
		setAttr("storelist", storeService.chooseAllStore());	
		render("storeList.jsp");
	}
	/**
	 * 商品详情
	 */
//	public void goodDetail(){
//		int id = getParaToInt("id",0);
//		if(id!=0){
//		Record goods=service.findGoodDetailById(id);
//		String gooditem=goods.getStr("goodItem");
//		String good_store=goods.getStr("good_store");
//			if(!StrKit.isBlank(gooditem)){
//				List<Record> goodItem=service.getGoodsItem(gooditem);
//					if(goodItem.size()>0){
//						setAttr("goodItem", goodItem);
//					}
//			}
//			if(!StrKit.isBlank(good_store)){
//				List<Record> store=service.getStore(good_store);
//					if(store.size()>0){
//						setAttr("store", store);
//					}
//			}
//		setAttr("goods", goods);
//		}
//		render("detail.jsp");
//	}
	/**
	 * 商品添加页面
	 */
	public void toAdd() {
		String LunBoNum = DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS") + CommonKit.buildRandomNum(4);
		int userid = getCurrentUser().getInt("id");
		List<Category> oneCategories = service.finOneCategory();
		setAttr("oneCategories", oneCategories);
		setAttr("LunBoNum", LunBoNum);
		setAttr("userid", userid);
		render("add.jsp");
	}
	/**
	 * 商品信息页面
	 */
	public void goodDetail() {
		int id = getParaToInt("id", 0);
		Admin admin = getCurrentUser();
		if ( admin == null ) {
			renderFailed();
		}
		int userid = admin.getInt("id");
		
		if (id != 0) {
			Record goods = service.findGoodDetailById(id);
			String gooditem = goods.getStr("goodItem");
			String good_store = goods.getStr("good_store");
			// String LunBoNum=goods.getStr("LunBoNum");
			if (!StrKit.isBlank(gooditem)) {
				List<Record> goodItem = service.getGoodsItem(gooditem);
				if (goodItem.size() > 0) {
					setAttr("goodItem", goodItem);
				}
			}
			if (!StrKit.isBlank(good_store)) {
				List<Record> store = service.getStore(good_store);
				if (store.size() > 0) {
					setAttr("store", store);
				}
			}
			
				List<Record> goodSpecs = service.getGoodSpec(id);
				if (goodSpecs.size() > 0) {
					setAttr("goodSpec", goodSpecs);
				}
			setAttr("goods", goods);
		}
		List<GoodsSale> goodsSales = service.findAllSale(id);
		if (goodsSales.size() > 0) {
			setAttr("goodsSales", goodsSales);
		}
		setAttr("userid", userid);
		
		Record toker = service.findtoker(id);
		setAttr("toker", toker);
		List<Category> oneCategories = service.finOneCategory();
		setAttr("oneCategories", oneCategories);
		List<Category> twoCategories = service.findTwoCategory();
		setAttr("twoCategories", twoCategories);
		List<Category> threeCategories = service.findThreeCategory();
		setAttr("threeCategories", threeCategories);
		List<Category> fourCategories = service.findFourCategory();
		setAttr("fourCategories", fourCategories);
		List<GoodsSaleItem> saleItems = service.findSaleItem(id);
		setAttr("saleItems", saleItems);
		render("detail.jsp");
	}
    /**
    * 驳回doCancel
    */
   public void toCancel(){
	   	String id=getPara("id");
	   	if(StrKit.isBlank(id)){
				renderFailed("id不能为空");
	   		return;
	   	}else{
	   		setAttr("id", id);
	   		render("doCancel.jsp"); 
	   	}
   }
	 /**
     * 驳回doCancel
     */
    public void doCancel(){
    	String id=getPara("id");
    	String reason=getPara("reason");
    	String checktime=DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss");
    	if(StrKit.isBlank(id)){
			renderFailed("参数id不能为空");
    		return;
    	}else{
    		int i= service.doCancel(id,reason,checktime);
    		if(i==1){
    			renderSuccess(service.findById(Integer.valueOf(id)));
    			return ;
    		}else{
    			//3.其他情况
				renderFailed("驳回失败");
				return;
    		}
    	}
    }
    /**
     * 降权
     */
    public void tooDown(){
    	String id=getPara("id");
    	String checktime=DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss");
    	if(StrKit.isBlank(id)){
			renderFailed("参数id不能为空");
    		return;
    	}else{
    		int i= service.tooDown(id,checktime);
    		if(i==1){
    			renderSuccess(service.findById(Integer.valueOf(id)));
    			return ;
    		}else{
    			//3.其他情况
				renderFailed("降权失败");
				return;
    		}
    	}
    }
    /**
     * 通过审核 TODO
     */
    public void doAccept(){
    	String id=getPara("id");
    	String checktime=DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss");
    	if(StrKit.isBlank(id)){
			renderFailed("参数id不能为空");
    		return;
    	}else{
    		int i= service.doAccept(id,checktime);
    		int iid = Integer.parseInt(id);
			GoodsStore goods = service.findById(iid);
			int groupbuying = goods.get("groupbuying");
			if (groupbuying==2) {
				MsgSend.send(id, RabbitMQCode.Code.QUEUE_UP);
			}
    		if(i==1){
    			renderSuccess(service.findById(Integer.valueOf(id)));
    			return ;
    		}else{
    			//3.其他情况
				renderFailed("审核失败");
				return;
    		}
    	}
    }
  //通过本页全部待审核
  	public void toEditAll() {
  		String adIds = getPara("adIds");
  		String[] sadIds = adIds.split(",");
  		String checktime=DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss");
  		for (String id : sadIds) {
  			//循环当前商品id，查看状态，如果为1则通过审核改为2否则不变
  			int goodsid = Integer.parseInt(id);
  			System.out.println(goodsid);
  			GoodsStore goodsStore = service.findById(goodsid);
  			int state = goodsStore.getInt("state");
  			System.out.println(state+"statestatestate");
  			
  			if (state==1) {
				service.doAccept(id, checktime);
			}
  		}
  		renderSuccess();
  	}
    /**
     * 删除商品
     */
    public void delete(){
    	String id=getPara("id");
    	if(StrKit.isBlank(id)){
			renderFailed("参数sellerId不能为空");
    		return;
    	}else{
    		GoodsStore goods=service.findById(Integer.valueOf(id));
    		if (!StrKit.isBlank(goods.getStr("uptime"))) {
    			renderFailed("该商品已经产生数据，禁止删除！");
        		return;
			}
    		if(service.delete(goods)){
    			renderSuccess();
    			return ;
    		}else{
    			//3.其他情况
				renderFailed("删除失败");
				return;
    		}
    	}
    }
	 
    /**
	 * 图文详情
	 */
	public void imgdetail() {
		UploadFile thumb = getFile();
		Map<String, Object> map = new HashMap<String, Object>();
		if (thumb != null) {
			String thumbFileName;
			String dir = DirKit.getDir(DirKit.GOODS_DETAIL);
			try {
				thumbFileName = uploadToFtp(dir, thumb);
				map.put("error", 0);
				map.put("url", PropKit.get("constants.ftppath").concat(dir).concat(thumbFileName));
				renderJson(map);
				return;
			} catch (IOException e) {
				e.printStackTrace();
				logger.debug("上传图片失败");
				map.put("error", 1);
				map.put("message", "图片上传失败");
				renderJson(map);
			}
		} else {
			map.put("error", 1);
			map.put("message", "图片为空");
			renderJson(map);
		}
	}
	/**
	 * 分公司产品文本编辑中图片上传
	 */
	public void uploadimg() {
		UploadFile thumb = getFile();
		Map<String, Object> map = new HashMap<String, Object>();
		if (thumb != null) {
			String thumbFileName;
			String dir = DirKit.getDir(DirKit.GOODS_DETAIL);
			try {
				thumbFileName = uploadToFtp(dir, thumb);
				map.put("error", 0);
				map.put("url", PropKit.get("constants.ftppath").concat(dir).concat(thumbFileName));
				renderJson(map);
				return;
			} catch (IOException e) {
				e.printStackTrace();
				logger.debug("上传图片失败");
				map.put("error", 1);
				map.put("message", "图片上传失败");
				renderJson(map);
			}
		} else {
			map.put("error", 1);
			map.put("message", "图片为空");
			renderJson(map);
		}
	}

	/**
	 * 图片列表
	 */
	public void imageIndex() {
		setAttr("LunBoNum", getPara(0));
		render("imageList.jsp");
	}

	/**
	 * 图片分页
	 */
	public void imagePage() {
		renderSuccess(service.findAllImages(getPara(0)));
	}

	/**
	 * 图片排序
	 */
	public void doImageSort() {
		Map<String, String[]> params = getParaMap();
		if (params != null && params.size() != 0 && params.containsKey("sortKey")) {
			String sortKey = params.get("sortKey")[0];
			Map<String, String> sortMap = new HashMap<String, String>();
			for (String key : params.keySet()) {
				if (!key.equals("sortKey")) {
					String id = key.replace(sortKey, "");
					String no = params.get(key)[0];
					if (StrKit.isBlank(no) || no.length() > 3) {
						no = "0";
					}
					sortMap.put(id, no);
				}
			}
			service.sortImages(sortMap);
			renderSuccess();
			return;
		}
		renderFailed();
	}

	/**
	 * 添加图片
	 */
	public void toImageAdd() {
		setAttr("LunBoNum", getPara(0));
		render("imageAdd.jsp");
	}

	/**
	 * 添加图片方法
	 * 
	 * @return -1：异常，0：成功，1：图片为空，2：图片上传失败
	 */
	public void doImageAdd() {
		List<UploadFile> file = getFiles("thumb");
		System.out.println("file"+file);
		System.out.println("file.size"+file.size());
		logger.info(""+file.size());
		if (file.isEmpty()) {
			renderFailed("轮播图片不能为空！");
			return;
		}else if (file.size() > 20) {
			renderFailed("轮播图一次最多上传20张！");
			return;
		}
		String LunBoNum = getPara("lunbonum");
		// 保存
		// 如果上传了图片，则上传至FTP，并记录图片文件名
		List<GoodsBaseImages> fileList = new ArrayList<>();
		
		boolean isSuccess = false;
		for(int i=0; i<file.size(); i++) {
			UploadFile thumb = file.get(i);
			System.out.println("thumb"+thumb);
			if (thumb != null) {
				String thumbFileName;
				String dir = DirKit.getDir(DirKit.GOODS_IMAGES);
				try {
					thumbFileName = uploadToFtp(dir, thumb);
				} catch (IOException e) {
					e.printStackTrace();
					renderResult(2);
					return;
				}
				GoodsBaseImages image = new GoodsBaseImages().set("LunBoNum", LunBoNum).set("thumb",
						dir.concat(thumbFileName));
				if (service.addImage(image)) {
					fileList.add(image);
					System.out.println("fileList"+fileList);
					isSuccess = true;
				}else {
					isSuccess = false;
				}
			} else {
				renderResult(1);
				return;
			}
		}
		if (isSuccess) {
			renderResult(0,fileList);
		} else {
			renderResult(1);
		}
		
	}

	/**
	 * 设置图片为商品LOGO
	 * 
	 * @return -1：异常，0：成功
	 */
	public void doSetImageLogo() {
		int id = getParaToInt(0, 0);
		int goodsid = getParaToInt("goodsid");
		if (id != 0 && service.setImageLogo(goodsid, id)) {
			renderSuccess();
			return;
		}
		renderFailed();
	}

	/**
	 * 删除图片
	 * 
	 * @return -1：删除失败，0：删除成功
	 */
	public void doImageDelete() {
		int id = getParaToInt(0, 0);
		if (id != 0 && service.delImage(id)) {
			renderSuccess();
			return;
		}
		renderFailed();
	}

	/**
	 * 添加详情图片列表
	 */
	public void imageDetailIndex() {
		setAttr("LunBoNum", getPara(0));
		render("detailImgList.jsp");
	}

	/**
	 * 详情图片分页
	 */
	public void imageDetailPage() {

		renderSuccess(service.findDetailImages(getPara(0)));
	}

	/**
	 * 详情图片排序
	 */
	public void doDetailSort() {
		Map<String, String[]> params = getParaMap();
		if (params != null && params.size() != 0 && params.containsKey("sortKey")) {
			String sortKey = params.get("sortKey")[0];
			Map<String, String> sortMap = new HashMap<String, String>();
			for (String key : params.keySet()) {
				if (!key.equals("sortKey")) {
					String id = key.replace(sortKey, "");
					String no = params.get(key)[0];
					if (StrKit.isBlank(no) || no.length() > 3) {
						no = "0";
					}
					sortMap.put(id, no);
				}
			}
			service.sortDetailImages(sortMap);
			renderSuccess();
			return;
		}
		renderFailed();
	}

	/**
	 * 添加详情图片页面
	 */
	public void toImageDetailAdd() {
		setAttr("LunBoNum", getPara(0));
		render("ImgDetailAdd.jsp");
	}
	
	/**
	 * 添加详情图片方法
	 * 
	 * @return -1：异常，0：成功，1：图片为空，2：图片上传失败
	 */
	public void doImageDetailAdd() {
		
		List<UploadFile> file = getFiles();
		logger.info(""+file.size());
		if (file.isEmpty()) {
			renderFailed("详情图片不能为空！");
			return;
		}else if (file.size() > 20) {
			renderFailed("详情图一次最多上传20张！");
			return;
		}
		// 保存
		String LunBoNum = getPara("LunBoNum");
		// 如果上传了图片，则上传至FTP，并记录图片文件名
		List<DetailsImg> fileList = new ArrayList<>();
		boolean isSuccess = false;
		for(int i=0; i<file.size(); i++) {
			UploadFile thumb = file.get(i);
			if (thumb != null) {
				String thumbFileName;
				String dir = DirKit.getDir(DirKit.GOODS_IMAGES);
				try {
					thumbFileName = uploadToFtp(dir, thumb);
				} catch (IOException e) {
					e.printStackTrace();
					renderResult(2);
					return;
				}
				DetailsImg image = new DetailsImg().set("LunBoNum", LunBoNum).set("thumb", dir.concat(thumbFileName));
			
				if (service.addDetailImage(image)) {
					fileList.add(image);
					isSuccess = true;
				}else {
					isSuccess = false;
				}
				
			} else {
				renderResult(1);
				return;
			}
		}
		if (isSuccess) {
			renderResult(0,fileList);
		} else {
			renderResult(1);
		}

	}

	/**
	 * 删除添加详情图片
	 * 
	 * @return -1：删除失败，0：删除成功
	 */
	public void doDetailImageDelete() {
		int id = getParaToInt(0, 0);
		if (id != 0 && service.delDetailImage(id)) {
			renderSuccess();
			return;
		}
		renderFailed();
	}
    /**
     * 分配标签
     */
    
    public void addTitle(){
    	int goodsId=getParaToInt("goodsId",0);
    	String titleCord=getPara("titleCord");
    	if(goodsId!=0){
    		GoodsStore goods=goodstoreService.findGoodById(goodsId);
            if(goods!=null){
            	goods.set("titleCord" , titleCord);
            	goodstoreService.update(goods);
            	renderSuccess();
            	return ;
            }
    	}
    	renderFailed("分配标签失败");
    	return;
    }
    /**
	 * 下架 TODO
	 */

	public void doDown() {
		String id = getPara("id");
		String downtime = DatetimeKit.getFormatDate("yyyy-MM-dd-hh-mm");
		// System.out.println(checktime);
		if (StrKit.isBlank(id)) {
			renderFailed("参数id不能为空");
			return;
		} else {
			int i = service.doDown(id, downtime);
			GoodsStore goods = service.findById(Integer.parseInt(id));
			int groupbuying = goods.get("groupbuying");
			if(groupbuying == 2){
				MsgSend.send(id, RabbitMQCode.Code.QUEUE_DOWN);
			}
			
			if (i == 1) {
				renderSuccess(service.findById(Integer.valueOf(id)));
				return;
			} else {
				// 3.其他情况
				renderFailed("下架失败");
				return;
			}
		}
	}
	/**
	 * 上架 
	 */
	public void doUp() {
		String id = getPara("id");
		String createDate = DatetimeKit.getFormatDate("yyyy-MM-dd-HH-mm-ss");
		if (StrKit.isBlank(id)) {
			renderFailed("参数id不能为空");
			return;
		}
		//将id转为int类型的goodsid
		int goodsid = Integer.parseInt(id);
		GoodsStore goodsStore = service.findById(goodsid);
		int groupbuying = goodsStore.get("groupbuying");
		System.out.println(groupbuying);
		List<GoodsSale> allSale = service.findAllSale(goodsid);
		if (service.findTemBygoodsid(goodsid)==null&&groupbuying==1) {
			renderFailed("请点击模板绑定模板");
			return;
		}
		if (allSale.isEmpty()&&groupbuying==1) {
			renderFailed("请至少填写一条销售信息");
			return;
		} else {
			int i = service.doUp(id, createDate);
			
			if (i == 1) {
				renderSuccess(service.findById(Integer.valueOf(id)));
				return;
			} else {
				// 3.其他情况
				renderFailed("下架失败");
				return;
			}
		
		}
	}
	/**
	 * 修改商品信息页面
	 */
	public void toEdit() {
		int id = getParaToInt(0, 0);
		int userid=getCurrentUser().getInt("id");
		if (id != 0) {
			Record goods = service.findGoodDetailById(id);
			String gooditem = goods.getStr("goodItem");
			String good_store = goods.getStr("good_store");
			// String LunBoNum=goods.getStr("LunBoNum");
			if (!StrKit.isBlank(gooditem)) {
				List<Record> goodItem = service.getGoodsItem(gooditem);
				if (goodItem.size() > 0) {
					setAttr("goodItem", goodItem);
				}
			}
			if (!StrKit.isBlank(good_store)) {
				List<Record> store = service.getStore(good_store);
				if (store.size() > 0) {
					setAttr("store", store);
				}
			}
			
				List<Record> goodSpecs = service.getGoodSpec(id);
				if (goodSpecs.size() > 0) {
					setAttr("goodSpecs", goodSpecs);
				}
				List<GoodsSale> goodsSales = service.findAllSale(id);
				if (goodsSales.size() > 0) {
					setAttr("goodsSales", goodsSales);
				}
			
			setAttr("goods", goods);

		}
		List<Category> oneCategories = service.finOneCategory();
		setAttr("oneCategories", oneCategories);
		List<Category> twoCategories = service.findTwoCategory();
		setAttr("twoCategories", twoCategories);
		List<Category> threeCategories = service.findThreeCategory();
		setAttr("threeCategories", threeCategories);
		List<Category> fourCategories = service.findFourCategory();
		setAttr("fourCategories", fourCategories);
		setAttr("userid", userid);
		render("edit.jsp");
	}
	/**
	 * 二级分类
	 */
	public void categoryonid(){
		String[] categoryonid = getParaValues("categoryonid");
		String str = java.lang.String.join("','", categoryonid);
		renderSuccess(service.finTwoCategory(str));
	}
	/**
	 * 三级分类
	 */
	public void categorytwid(){
		String[] categorytwid = getParaValues("categorytwid");
		String str = java.lang.String.join("','", categorytwid);
		renderSuccess(service.finThreeCategory(str));
	}
	/**
	 * 四级分类
	 */
	public void categorythid(){
		String[] categorythid = getParaValues("categorythid");
		String str = java.lang.String.join("','", categorythid);
		renderSuccess(service.finFourCategory(str));
	}
	/**
	 * 添加商品
	 */
	public void doAdd() {
		int userid=getCurrentUser().getInt("id");
		/* 商品基本信息 */
		// 商品图片
		UploadFile goodsthumb = getFile("goodsthumb");
		//客服二维码
		UploadFile Qrthumb = getFile("Qrthumb");
		// 商品名称
		String name = getPara("names");
		// 所属类别：
		String categoryonid = getPara("categoryonid");
		String categorytwid = getPara("categorytwid");
		String categorythid = getPara("categorythid");
		String categoryfoid = getPara("categoryfoid");
		
		String sellPrice = getPara("sellPrice");
		/*
		 * String categorythid = getPara("categorythid");
		 *  String categoryfoid =getPara("categoryfoid");
		 */
		// 分公司id
		String[] storeids = getParaValues("checks");
		if (storeids == null) {
			renderResult(3);
			return;
		}
		String goodstore = DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS") + CommonKit.buildRandomNum(4);
		for (int i = 0; i < storeids.length; i++) {
			GoodsStoreRel gsr = new GoodsStoreRel();
			String store = storeids[i];
			gsr.set("storeid", store).set("goodstore", goodstore).save();
		}
		String goodsNum="";
		if(userid==20){
			goodsNum=getPara("goodsNum");
		}
		//是否团购
		int groupbuying = getParaToInt("groupbuying", 1);
		//团购价格
		String gbprice = getPara("gbprice",null);
		//团购价格
		String countnum = getPara("countnum",null);
		//团购人数
		String gbperson = getPara("gbperson",null);
		//团购方法
		int gbmethod = getParaToInt("gbmethod",1);
		//团购免单人数
		int gbfreeperson = getParaToInt("gbfreeperson",0);
		//付费人数
		int gbpayperson = getParaToInt("gbpayperson",0);
		// 团购时间
		String sgbbegintime = getPara("gbbegintime",null);
		String sgbendtime = getPara("gbendtime",null);
		String gbbegintime =null;
		String gbendtime =null;
		if (sgbbegintime!=null) {
			gbbegintime = sgbbegintime+ " 00:00:00";
		}
		if (sgbendtime!=null) {
			gbendtime = sgbendtime+ " 23:59:59";
		}
		//拼团失效时间
		int gbLostTime = getParaToInt("gbLostTime", 0);
		//是否赠送优惠
		int zsactivity = getParaToInt("zsactivity", 1);
		//优惠数量
		//积分值
		String zspointnum = getPara("zspointnum",null);
		//抵扣券
		String zsdedunum = getPara("zsdedunum",null);
		//优惠券
		String zscouponnum = getPara("zscouponnum",null);
		
		// 添加分公司数
		int countStore = getParaToInt("storeid", 0);
		// 分公司价
		/*String marketPrice = getPara("marketPrice");
		// 库存
		int stock = getParaToInt("stock", 0);*/
		
		/* 商品内容前端隐藏 ************************start*********************************/
		// 宝贝内容 套餐
		String goodItem = DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS") + CommonKit.buildRandomNum(4);
		String[] names = getParaValues("name");
		String[] numbers = getParaValues("number");
		String[] prices = getParaValues("price");
		if (StrKit.notBlank(prices)) {
			for (int i = 0; i < prices.length; i++) {
				GoodsItem goodsitem = new GoodsItem();
				String aname = names[i];
				String anumber = numbers[i];
				String aprice = prices[i];
				goodsitem.set("itemname", aname).set("itemmoney", aprice).set("itemnum", anumber).set("goodItem",
						goodItem);
				service.addItem(goodsitem);
			}
		} 
	/*	else {
			renderResult(10);
			return;
		}*/
		// 添加可选项服务
		String kemark = getPara("kemark");

		// 售卖时间
		/*String starttime = getPara("sBeginDate");
		String endtime = getPara("sEndDate");*/
		
		
		/* 商品内容前端隐藏 ************************end*********************************/
		// 商品类型
		int goodtype = getParaToInt("goods", 1);
		// 团购时间类型
		int times = getParaToInt("times", 1);
		// 团购时间
		String tuanStarttime = getPara("beginDate");
		String tuanEndtime = getPara("endDate");
		// 可用时间
		int timetype = getParaToInt("keyong", 1);
		int busetime = getParaToInt("starttime", 0);
		int eusetime = getParaToInt("endtime", 0);
		// 购买上限
		int buytype = getParaToInt("goumai", 1);
		int buycount = getParaToInt("zdsx", 1);
		// 预约
		int yutype = getParaToInt("yuyue", 1);
		int yuday = getParaToInt("yyts", 0);
		// 适用人数
		int couper = getParaToInt("shiyongrenshu", 1);
		int jyrs = getParaToInt("jyrs", 0);
		int zdrs = getParaToInt("zdrs", 0);
		// 性别限定
		int shiyongren = getParaToInt("xingbiexianding", 1);
		// 使用规则
		int regul = getParaToInt("shiyongguize", 1);
		// 补充内容
		String content = getPara("bucong");
		/* 商品详情 */

		// 文字简介
		String shortInfo = getPara("shortinfo");
		String beizhu = getPara("beizhu");
		
		
		// 轮播图片和详情图片
		String LunBoNum = getPara("LunBoNum");
		if (goodsthumb == null) {
			renderResult(7);
			return;
		} else if (groupbuying == 2 && countnum == null) {
			renderResult(5);
			return;
		} else if (Qrthumb == null) {
			renderResult(9);
			return;
		} else if (zsactivity == 2 && StrKit.isBlank(zspointnum) && StrKit.isBlank(zsdedunum) && StrKit.isBlank(zscouponnum)) {
			renderResult(16);
			return;
		} else {
			GoodsStore goods = new GoodsStore().set("name", name)
					.set("categoryonid", Integer.valueOf(categoryonid).intValue())
					.set("categorytwid", Integer.valueOf(categorytwid).intValue())
					.set("categorythid", Integer.valueOf(categorythid).intValue())
					.set("categoryfoid", Integer.valueOf(categoryfoid).intValue())
					.set("good_store", goodstore)
					.set("sellPrice", sellPrice)
					.set("countStore", countStore).set("state", 3)
					.set("createDate", DatetimeKit.getFormatDate("yyyy-MM-dd-HH-mm-ss"))
					.set("goodItem", goodItem).set("goodtype", goodtype)
					.set("times", times).set("timetype", timetype).set("busetime", busetime).set("kemark", kemark)
					.set("eusertime", eusetime).set("buytype", buytype).set("buycount", buycount).set("yutype", yutype)
					.set("yuday", yuday).set("couper", couper).set("jyrs", jyrs).set("zdrs", zdrs)
					.set("shiyongren", shiyongren).set("regul", regul).set("content", content)
					.set("shortInfo", shortInfo).set("ftype", Integer.valueOf(categoryonid).intValue()).set("pstate", 1)
					.set("LunBoNum", LunBoNum).set("beizhu", beizhu).set("goodsNum", goodsNum)
					.set("groupbuying", groupbuying).set("gbprice", gbprice).set("gbperson", gbperson).set("gbLostTime", gbLostTime)
					.set("countnum", countnum)
					.set("zsactivity", zsactivity)
					.set("zspointnum", zspointnum).set("zsdedunum", zsdedunum).set("zscouponnum", zscouponnum)
					.set("gbmethod", gbmethod).set("gbfreeperson", gbfreeperson).set("gbpayperson", gbpayperson)
					;
			if (!StrKit.isBlank(tuanStarttime)) {
				goods.set("tuanStarttime", tuanStarttime);
			}
			if (!StrKit.isBlank(tuanEndtime)) {
				goods.set("tuanEndtime", tuanEndtime);
			}
			//判断团购时间是否空
			if (!StrKit.isBlank(gbbegintime)) {
				goods.set("gbbegintime", gbbegintime);
			}
			if (!StrKit.isBlank(gbendtime)) {
				goods.set("gbendtime", gbendtime);
			}
			// 如果上传了图片，则上传至FTP，并记录图片文件名
			if (goodsthumb != null) {
				String thumbFileName;
				String dir = DirKit.getDir(DirKit.GOODS_BASE);
				try {
					thumbFileName = uploadToFtp(dir, goodsthumb);
				} catch (IOException e) {
					e.printStackTrace();
					renderResult(12);
					return;
				}
				goods.set("thumb", dir.concat(thumbFileName));
			}
			if (Qrthumb != null) {
				String QrthumbFileName;
				String Qrthumbdir = DirKit.getDir(DirKit.GOODS_BASE);
				try {
					QrthumbFileName = uploadToFtp(Qrthumbdir, Qrthumb);
				} catch (IOException e) {
					e.printStackTrace();
					renderResult(6);
					return;
				}
				goods.set("Qrthumb", Qrthumbdir.concat(QrthumbFileName));
			}
			service.add(goods);
		}
		renderFailed();
	}
	/**
	 * 销售信息页面
	 */
	public void sale() {
		//获取商品id
		int goodsid = getParaToInt(0, 0);
		GoodsStore goods = service.findByIdGoods(goodsid);
		int gb = goods.get("groupbuying");
		if (gb==2) {
			renderFailed("团购商品，该模块不可用");
			return;
		}
		//根据商品id查询对应的SKU，返回前端进行判断
		List<GoodsSale> listSale = service.findAllSale(goodsid);
		List<String> listSpec = new ArrayList<>();
		for (GoodsSale goodsSale : listSale) {
			String sgoodsSpec = goodsSale.get("goodsSpec");
			String[] specs = sgoodsSpec.split(",");
			for (int i = 0; i < specs.length; i++) {
				String spec = specs[i];
				listSpec.add(spec);
			}
		}
		//查询对应的模板
		GoodsSaleGT saleGT = service.findTemBygoodsid(goodsid);
		if (saleGT == null) {
			 renderFailed("请点击模板绑定模板"); 
			 return;
		} else {
			//获取对应的模板id
			int tid = saleGT.get("templateid");
			//查询对应的模板信息
			GoodsSaleTemplate goodsTemplate = service.findTemplateById(tid);
			//获取模板中的规格信息
			/*if (condition) {
				
			}*/
			String specs = goodsTemplate.get("spec");
			//对规格信息进行分割
			String[] sspecs = specs.split(",");
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			for (int i = 0; i < sspecs.length; i++) {
				String sspecid = sspecs[i];
				//转换为int
				int specid = Integer.parseInt(sspecid);
				GoodsSaleSpec spec = service.findSpecByid(specid);
				String specName = spec.get("specName");
				//根据规格下所有option的参数
				List<GoodsSaleOption> options = service.finOptionById(specid);
				List<String>  listoptionname = new ArrayList<String>();
				Map<String,Object> map = new HashMap<>();
				for (GoodsSaleOption option : options) {
					String optionName = option.get("optionName");
					listoptionname.add(optionName);
					map.put("specName", specName);
					map.put("optionName", listoptionname);
				}
				list.add(map);
			}
			setAttr("listSpec", listSpec);
			setAttr("listSale", listSale);
			setAttr("goodsid", goodsid);
			setAttr("list", list);
			render("sale.jsp");
		}
	}
	public void addSku(){
		int goodsid = getParaToInt("goodsid");
		//查询商品详情

		//查询对应的模板
		GoodsSaleGT saleGT = service.findTemBygoodsid(goodsid);
		//获取对应的模板id
		int templateid = saleGT.get("templateid");
		//删除原有的销售信息，重新添加
		service.deteleSale(goodsid);
		String[] KskuPrice = getParaValues("KskuPrice");//商品售价
		String[] KskuStock = getParaValues("KskuStock");//商品库存
		String[] KskuCoding = getParaValues("KskuCoding");//商品内部码
		String[] KskuBarcode = getParaValues("KskuBarcode");//商品国际码
		String[] KpropvalnameArr = getParaValues("KpropvalnameArr");//商品规格参数
		if (KpropvalnameArr == null) {
			renderResult(2);
			return;
		} else {
			if (KskuPrice != null && KskuPrice.length > 0) {
				for (int i = 0; i < KskuPrice.length; i++) {
					GoodsSale goodsSale = new GoodsSale();
					String sKpropvalnameArr = KpropvalnameArr[i];
					String sKskuStock = KskuStock[i];
					String sKskuCoding = KskuCoding[i];
					String sKskuBarcode = KskuBarcode[i];
					String sKskuPrice = KskuPrice[i];
					
					goodsSale.set("title", sKpropvalnameArr)//商品名称
							.set("goodsSpec", sKpropvalnameArr)//商品规格参数
							.set("salestock", sKskuStock)//商品库存
							.set("coding", sKskuCoding)//商品内部码
							.set("barcode", sKskuBarcode)//商品国际码
							.set("saleprice", sKskuPrice)//商品售价
							.set("goodsid", goodsid)//商品id
							.set("templateid", templateid)//模板id
							.save();
				}
			}
		}
		renderSuccess();
	}

	/**
	 * 模板绑定页面
	 */
	public void Tem() {
		List<GoodsSaleTemplate> allGoodsTemplates = service.findAllGoodsTemplates();
		int goodsid = getParaToInt(0, 0);
		if(service.findTemBygoodsid(goodsid) != null){
			GoodsSaleGT saleGT = service.findTemBygoodsid(goodsid);
			setAttr("saleGT", saleGT);
		}
		GoodsStore goods = service.findByIdGoods(goodsid);
		int gb = goods.get("groupbuying");
		if (gb==2) {
			renderFailed("团购商品，该模块不可用");
			return;
		}
		List<GoodsItem> allItems = service.findAllItems(goodsid);
		setAttr("allItems", allItems);
		setAttr("goodsid", goodsid);
		setAttr("allGoodsTemplates", allGoodsTemplates);
		render("template.jsp");
		
	}
	/**
	 * 模板绑定
	 */
	public void template() {
		//模板的id
		int templateid = getParaToInt("templateid", 0);
		//商品的id
		int goodsid = getParaToInt("goodsid", 0);
		if(service.findTemBygoodsid(goodsid) == null){
			GoodsSaleGT goodsSaleGT = new GoodsSaleGT();
			goodsSaleGT.set("templateid", templateid).set("goodsid", goodsid);
			;
			if (service.savegt(goodsSaleGT)) {
				//扩展属性集合
				String[] siname = getParaValues("iname");
				String[] sidetail = getParaValues("idetail");
				
				if (siname != null && siname.length > 0) {
					for (int i = 0; i < siname.length; i++) {
						//扩展属性
						String iname = siname[i];
						String idetail = sidetail[i];
						GoodsSaleItem goodsSaleItem = new GoodsSaleItem().set("iname", iname)//商品规格名称
								.set("idetail", idetail)
								.set("goodsid", goodsid)
								;
						service.saveItem(goodsSaleItem);
					}
				}
			}
		} else if (service.findTemBygoodsid(goodsid).set("templateid", templateid).update()) {
			service.deleteitem(goodsid);
			//扩展属性集合
			String[] siname = getParaValues("iname");
			String[] sidetail = getParaValues("idetail");
			
			if (siname != null && siname.length > 0) {
				for (int i = 0; i < siname.length; i++) {
					//扩展属性
					String iname = siname[i];
					String idetail = sidetail[i];
					GoodsSaleItem goodsSaleItem = new GoodsSaleItem().set("iname", iname)//商品规格名称
							.set("idetail", idetail)
							.set("goodsid", goodsid)
							;
					service.saveItem(goodsSaleItem);
				}
			}
		}
		renderFailed();
	}
		
	/**
	 * 修改商品信息并保存
	 */
	public void doEdit() {
		
		/*
		 * 商品基本信息 由于不是同一张表，所以修改的操作是先把原始的数据删除掉 在进行重新的写入。
		 */
		// 商品图片
		UploadFile goodsthumb = getFile("goodsthumb");
		// 客服二维码
		UploadFile Qrthumb = getFile("Qrthumb");
		int userid=getCurrentUser().getInt("id");
		// 商品名称
		String name = getPara("names");
		// 商品名称
		String countnum = getPara("countnum",null);
		// 所属类别：
		String categoryonid = getPara("categoryonid");
		String categorytwid = getPara("categorytwid");
		String categorythid = getPara("categorythid");
		String categoryfoid = getPara("categoryfoid");
		System.out.println(categorythid);
		System.out.println(categoryfoid);
		int id = getParaToInt("id");
		Record good = service.findGoodDetailById(id);
		String gooditem = good.getStr("goodItem");
		// int item= service.deteleItem(gooditem);
		service.deteleItem(gooditem);
		String goodstore = good.getStr("good_store");
		
		String sellPrice = getPara("sellPrice");

		service.detelepayType(id);
		//商品货号
		String goodsNum="";
		if(userid==20){
			goodsNum=getPara("goodsNum");
		}
		//是否团购
		int groupbuying = getParaToInt("groupbuying", 1);
		//团购价格
		String gbprice = getPara("gbprice",null);
		//团购人数
		String gbperson = getPara("gbperson",null);
		//团购方法
		int gbmethod = getParaToInt("gbmethod",1);
		//团购免单人数
		int gbfreeperson = getParaToInt("gbfreeperson",0);
		//团购人数
		int gbpayperson = getParaToInt("gbpayperson",0);
		// 团购时间
		String sgbbegintime = getPara("gbbegintime",null);
		String gbbegintime = null;
		if (sgbbegintime!=null) {
			gbbegintime = sgbbegintime+ " 00:00:00";
		}
		String sgbendtime = getPara("gbendtime",null);
		String gbendtime = null;
		if (sgbendtime!=null) {
			gbendtime = sgbendtime+ " 23:59:59";
		}
		//拼团失效时间
		int gbLostTime = getParaToInt("gbLostTime", 0);
		//是否赠送优惠
		int zsactivity = getParaToInt("zsactivity", 1);
		//优惠数量
		//积分值
		String zspointnum = getPara("zspointnum",null);
		//抵扣券
		String zsdedunum = getPara("zsdedunum",null);
		//优惠券
		String zscouponnum = getPara("zscouponnum",null);
		// 分公司价
		/* 商品内容前端隐藏 ************************start*********************************/
		// 宝贝内容
		String[] names = getParaValues("name");
		String[] numbers = getParaValues("number");
		String[] prices = getParaValues("price");
		if (names != null && names.length > 0) {
			for (int i = 0; i < names.length; i++) {
				GoodsItem goodsitem = new GoodsItem();
				String aname = names[i];
				String anumber = numbers[i];
				String aprice = prices[i];
				goodsitem.set("itemname", aname).set("itemmoney", aprice).set("goodItem", gooditem)
						.set("itemnum", anumber).save();
			}
		}/* else {
			renderResult(10);
			return;
		}*/
		// 可选服务
		String kemark = getPara("kemark");
		// 售卖时间
		/*String starttime = getPara("sBeginDate");
		String endtime = getPara("sEndDate");*/
		
		/* 商品内容前端隐藏 ************************end*********************************/
		// 商品类型
		int goodtype = getParaToInt("goods", 1);
		// 轮播图
		String LunBoNum = getPara("LunBoNum");
		// 团购时间类型
		int times = getParaToInt("times", 1);
		// 团购时间
		String tuanStarttime = getPara("beginDate");
		String tuanEndtime = getPara("endDate");
		// 可用时间
		int timetype = getParaToInt("keyong", 1);
		int busetime = getParaToInt("starttime", 0);
		int eusetime = getParaToInt("endtime", 0);
		// 购买上限
		int buytype = getParaToInt("goumai", 1);
		int buycount = getParaToInt("zdsx", 0);
		// 预约
		int yutype = getParaToInt("yuyue", 1);
		int yuday = getParaToInt("yyts", 0);
		// 适用人数
		int couper = getParaToInt("shiyongrenshu", 1);
		int jyrs = getParaToInt("jyrs", 0);
		int zdrs = getParaToInt("zdrs", 0);
		if(jyrs!=0){
			service.detelezdrs(id);
		}if(zdrs!=0){
			service.detelejyrs(id);
		}
		// 性别限定
		int shiyongren = getParaToInt("xingbiexianding", 1);
		// 使用规则
		int regul = getParaToInt("shiyongguize", 1);
		// 补充内容
		String content = getPara("bucong");
	
		// 备注
		String beizhu = getPara("beizhu");		
		/* 商品详情 */

		/*String[] KspecName = getParaValues("KspecName"); //商品规格名称
*/		// 文字简介
		String shortInfo = getPara("shortinfo");
		String thumbOld = getPara("thumbOld");
		String QrthumbOld = getPara("QrthumbOld");
		if (StrKit.isBlank(name)) {
			renderResult(1);
			return;
		} else if (StrKit.isBlank(categoryonid) || StrKit.isBlank(categorytwid)) {
			renderResult(2);
			return;
		/*} else if (StrKit.isBlank(marketPrice)) {
			renderResult(4);
			return;
		} else if (stock == 0) {
			renderResult(5);
			return;
		} else if (StrKit.isBlank(sellPrice)) {
			renderResult(6);
			return;
		} else if (!StrKit.notBlank(KspecName)) {
			renderResult(6);
			return;*/
		}else if (groupbuying == 2 && countnum == null) {
			renderResult(5);
			return;
		} else if ( goodsthumb == null&&thumbOld== null) {
			renderResult(7);
			return;
		}else if ( Qrthumb == null&&QrthumbOld== null) {
			renderResult(9);
			return;
		} else if (zsactivity == 2 && StrKit.isBlank(zspointnum) && StrKit.isBlank(zsdedunum) && StrKit.isBlank(zscouponnum)) {
			renderResult(16);
			return;
		} else {
			// GoodsStore goods=new GoodsStore()
			GoodsStore goods = service.findByIdGoods(id).set("name", name)
					.set("categoryonid", Integer.valueOf(categoryonid).intValue())
					.set("categorytwid", Integer.valueOf(categorytwid).intValue())
					.set("categorythid", Integer.valueOf(categorythid).intValue())
					.set("categoryfoid", Integer.valueOf(categoryfoid).intValue())
					.set("good_store", goodstore)
					.set("sellPrice", sellPrice)
					/*.set("countStore", countStore)*/
					.set("state", 3)
					.set("createDate", DatetimeKit.getFormatDate("yyyy-MM-dd-HH-mm-ss"))
					.set("goodItem", gooditem).set("goodtype", goodtype)
					.set("LunBoNum", LunBoNum).set("times", times).set("timetype", timetype).set("kemark", kemark)
					.set("busetime", busetime).set("eusertime", eusetime).set("buytype", buytype)
					.set("buycount", buycount).set("yutype", yutype).set("yuday", yuday).set("couper", couper)
					.set("jyrs", jyrs).set("zdrs", zdrs).set("shiyongren", shiyongren).set("regul", regul)
					.set("content", content).set("shortInfo", shortInfo)
					.set("ftype", Integer.valueOf(categoryonid).intValue()).set("pstate", 1)
					.set("beizhu", beizhu).set("goodsNum", goodsNum)
					.set("groupbuying", groupbuying).set("gbprice", gbprice).set("gbperson", gbperson).set("gbLostTime", gbLostTime)
					.set("countnum", countnum)
					.set("zsactivity", zsactivity)
					.set("zspointnum", zspointnum).set("zsdedunum", zsdedunum).set("zscouponnum", zscouponnum)
					.set("gbmethod", gbmethod).set("gbfreeperson", gbfreeperson).set("gbpayperson", gbpayperson)
					;
			//set("marketPrice", UtilNumber.DoubleValueOf(marketPrice))  商品分公司价 放到t_bus_goods_spec表里
			//.set("stock", stock)  库存数量   迁移到t_bus_goods_spec表里  stocknum

			
			/*if (!StrKit.isBlank(starttime)) {
				goods.set("starttime", starttime);
			}
			if (!StrKit.isBlank(endtime)) {
				goods.set("endtime", endtime);
			}*/
			if (!StrKit.isBlank(tuanStarttime)) {
				goods.set("tuanStarttime", tuanStarttime);
			}
			if (!StrKit.isBlank(tuanEndtime)) {
				goods.set("tuanEndtime", tuanEndtime);
			}
			//判断团购时间是否空
			if (!StrKit.isBlank(gbbegintime)) {
				goods.set("gbbegintime", gbbegintime);
			}
			if (!StrKit.isBlank(gbendtime)) {
				goods.set("gbendtime", gbendtime);
			}
			// 如果上传了图片，则上传至FTP，并记录图片文件名
			if (goodsthumb != null) {
				String thumbFileName;
				String dir = DirKit.getDir(DirKit.GOODS_BASE);
				try {
					thumbFileName = uploadToFtp(dir, goodsthumb);
					deleteFromFtp(thumbOld);
				} catch (IOException e) {
					e.printStackTrace();
					renderResult(18);
					return;
				}
				goods.set("thumb", dir.concat(thumbFileName));
			}
			// 如果上传了客服二维码，则上传至FTP，并记录图片文件名
			if (Qrthumb != null) {
				String QrthumbFileName;
				String Qrthumbdir = DirKit.getDir(DirKit.GOODS_BASE);
				try {
					QrthumbFileName = uploadToFtp(Qrthumbdir, Qrthumb);
					deleteFromFtp(QrthumbOld);
				} catch (IOException e) {
					e.printStackTrace();
					renderResult(6);
					return;
				}
				goods.set("Qrthumb", Qrthumbdir.concat(QrthumbFileName));
			}
			// 保存
			if (service.updategood(goods)) {
				//商品ID
				int goodsid = service.findidByName(name);
				//销售信息
				String[] KpropvalnameArr = getParaValues("KpropvalnameArr");//Skuid
				String[] Ktemplateid = getParaValues("Ktemplateid");//Skuid
				String[] Ktitle = getParaValues("Ktitle");//Skuid
				String[] KskuPrice = getParaValues("KskuPrice");//Sku价格
				String[] KskuStock = getParaValues("KskuStock");//库存
				String[] KskuCoding = getParaValues("KskuCoding");//内部码
				String[] KskuBarcode = getParaValues("KskuBarcode");//国际码
				service.deteleSale(goodsid);
				if (KpropvalnameArr != null && KpropvalnameArr.length > 0) {
					//循环添加规格参数
					for (int i = 0; i < KpropvalnameArr.length; i++) {
						String sKpropvalnameArr = KpropvalnameArr[i];
						String sKtemplateid = Ktemplateid[i];
						String sKtitle = Ktitle[i];
						String sKskuPrice = KskuPrice[i];
						String sKskuStock = KskuStock[i];
						String sKskuCoding = KskuCoding[i];
						String sKskuBarcode = KskuBarcode[i];
						GoodsSale goodsSale = new GoodsSale();
						goodsSale.set("saleprice", UtilNumber.DoubleValueOf(sKskuPrice)).set("salestock", sKskuStock).set("coding", sKskuCoding).set("barcode", sKskuBarcode)
								.set("goodsSpec", sKpropvalnameArr).set("title", sKtitle).set("coding", sKskuCoding).set("templateid", sKtemplateid).set("goodsid", goodsid)
								.save();
					}
				} 
				//添加成功更新返回商品ID
				renderSuccess(service.findById(Integer.valueOf(id)));
				return;	
			}
		}
		renderFailed();
	}
	/**
	 * excel导出
	 */
	public void doExcel(){
		List<Pair> titles = new ArrayList<Pair>();
	    titles.add(new Pair("id", "商品ID"));
	    titles.add(new Pair("name", "商品名称"));
	    
	    titles.add(new Pair("oneName", "商品类别"));
	    titles.add(new Pair("groupbuying", "商品属性"));
	    titles.add(new Pair("tState", "是否拓客"));
	    titles.add(new Pair("sellerName", "发布公司"));
	    titles.add(new Pair("createDate", "申请时间"));
	  /*  titles.add(new Pair("stock", "库存数量"));
	    titles.add(new Pair("type", "支付方式"));
	    titles.add(new Pair("paytype", "积分类型"));
	    titles.add(new Pair("sellpoint", "所需积分"));
	    titles.add(new Pair("sellPrice", "现金价格"));*/
	    titles.add(new Pair("countStore", "上架分公司数"));
	    titles.add(new Pair("checktime", "审核时间"));
	    titles.add(new Pair("downtime", "下架时间"));
	    titles.add(new Pair("pstate", "当前状态"));
 		int sGoodId = getParaToInt("sGoodId",0);
		String sSellerId = getPara("sSellerId");
		String sGoodName = getPara("sGoodName");
		String sStoreId = getPara("sStoreId");
		int state = getParaToInt("sState",0);
		List<Record> list=service.findExcelByPage(sGoodId,sGoodName,sSellerId,sStoreId,state);
		List<Record> listz=new ArrayList<Record>();
		for (int i = 0; i < list.size(); i++) {
			Record record=new Record();
				record.set("id",list.get(i).get("id"));
				record.set("name", list.get(i).get("name"));
				record.set("oneName", list.get(i).get("oneName"));
				if(list.get(i).get("groupbuying").equals(1)){
					record.set("groupbuying", "常规");
				}else if(list.get(i).get("ftype").equals(2)){
					record.set("groupbuying", "团购");
				}
				if(list.get(i).get("tState")!=null&&list.get(i).get("tState").equals(1)){
					record.set("tState", "打开");
				}else {
					record.set("tState", "关闭");
				}
				record.set("sellerName", list.get(i).get("sellerName"));
				record.set("createDate", list.get(i).get("createDate"));
				/*record.set("stock", list.get(i).get("stock"));
				if(list.get(i).get("type").equals(1)){
					record.set("type", "货币");
				}else if(list.get(i).get("type").equals(2)){
					record.set("type", "积分");
				}else if(list.get(i).get("type").equals(3)){
					record.set("type", "货币积分");
				}
				if(list.get(i).get("paytype").equals(1)){
					record.set("paytype", "积分");
				}else if(list.get(i).get("paytype").equals(2)){
					record.set("paytype", "抵扣券");
				}else if(list.get(i).get("paytype").equals(3)){
					record.set("paytype", "惠券");
				}
				record.set("sellpoint", list.get(i).get("sellpoint"));
				record.set("sellPrice", list.get(i).get("sellPrice"));*/
				record.set("countStore", list.get(i).get("countStore"));
				record.set("checktime", list.get(i).get("checktime"));
				record.set("downtime", list.get(i).get("downtime"));
				if(list.get(i).get("pstate").equals(1)){
					if(list.get(i).get("state").equals(1)){
						record.set("pstate", "上架审核中");
					}else if(list.get(i).get("state").equals(2)){
						record.set("pstate", "上架");
					}else if(list.get(i).get("state").equals(3)){
						record.set("pstate", "下架");
					}
				}else if(list.get(i).get("pstate").equals(2)){
					record.set("pstate", "售罄");
				}else if (list.get(i).get("pstate").equals(3)){
					record.set("pstate", "降权");
				}
			listz.add(record);
 		}
		// 导出
		service.export(getResponse(), getRequest(),titles, listz);		
		renderNull();
	}
	
}
